#!/usr/bin/perl 
use CGI qw(:standard);
use lib '.';
use users;
use strict;
use warnings;

binmode STDOUT, ":utf8";
print header;
print start_html('Add Realm');
my %FORM;
foreach my $field (param()) 
{
    $FORM{$field} = param($field);
#warn ($field,"==", $FORM{$field});
}
if (exists $FORM{realmnum}) 
{
	my $realmnum=$FORM{realmnum};
	my $realmname=$FORM{realmname};
	#warn ($realmnum,"==",$realmname);
	#my $cookie = cookie(-name=>'realm', -value=>$search, -expires=>'+7d');
	#print end_html;
	my $realmfile = 'data/realm.psv';
	# open the realm file for read
	open(REALM,"<$realmfile") or &dienice("Can't open realm file.");
	#	flock(REALM, LOCK_EX);          # lock the file (exclusively)
	#	seek(REALM, 0, SEEK_SET);       # rewind to beginning
	my @realmf = <REALM>;            	# read entire file
	close(REALM);
	my $found="N";

	foreach my $i (@realmf)
	{
		chomp($i);
		my ($realm,$realmdesc) = split( /\|/, $i);
		if ( $realm eq $realmnum )
		{
			print p("Realm already exists!");
			print br();
			print hr();
			print a( {-href=>"changerealm.pl"}, "Realm Selector");
			print br();
	 		print a( {-href=>"menu.cgi"}, "Main Menu");
			$found="Y";
		}
	}
	if ( $found eq "N" )
	{
		print br();
		$realmnum =~ m/^([a-zA-Z0-9\._]+)$/ or die "Bad data in first argument";	

		print p("Adding new Realm $realmnum - $realmname");
		open(REALM,">$realmfile") or &dienice("Can't open realm file.");
		foreach my $i (@realmf)
		{
			chomp($i);
			my ($realm2,$realmdesc2) = split( /\|/, $i);
			print REALM "$realm2|$realmdesc2\n";			
		}
		print REALM "$realmnum|$realmname\n";
		close(REALM);
		print p("Realm File updated");
		my $myfile="data/alliance".".$realmnum";
		open my $ALLI, ">>:utf8", $myfile or die_nice("can't open $myfile file to write $!");
		print $ALLI "# $realmnum - $realmname\n";
		close $ALLI;
		print p("New alliance File created");
		open my $PLAYER, ">>:utf8", "data/players".".$realmnum" or die_nice("can't open PLAYERS".".$realmnum file to write $!");
		print $PLAYER "# $realmnum - $realmname\n";
		close $PLAYER;
		print p("New player name File created");
		open my $MAPF, ">>", "mapfile.$realmnum" or die_nice("can't open mapfile.$realmnum file to write $!");
		print $MAPF "{}";
		close $MAPF;
		print p("New Map File created");
	}
}
print br();
print br();
print a( {-href=>"changerealm.pl"}, "Realm Selector");
print br();
print a( {-href=>"menu.cgi"}, "Main Menu");
print end_html;
#print redirect(-location=>"changerealm.pl");
